package com.patsnap.data.npd.dw.common.compress;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.nio.ByteBuffer;

public class ByteBufferAdapter implements JsonSerializer<ByteBuffer>, JsonDeserializer<ByteBuffer> {

    public ByteBuffer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        try {
            if(json != null && !json.isJsonObject()){
                return StreamUtil.compressString(json.getAsString());
            }else{
                return null;
            }

        }
        catch (Exception e) {
            throw new JsonParseException(e);
        }
    }

    public JsonElement serialize(ByteBuffer src, Type typeOfSrc, JsonSerializationContext context) {
        String content = null;
        try {
            if(src != null){
                content = StreamUtil.decodeBinary2String(src);
                return new JsonPrimitive(content);
            }else{
                return null;
            }
        }
        catch (Exception e) {
        }
        return null;
    }

}
